import React, { useEffect, useState, useReducer } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Form, Col, Input, Row, Button, Divider, Table } from "antd";

import BillModel from "./BillModel";
import axios from "axios";
import head from "../common/head.js";
import "./index.css";

const initialState = {
  billModelStatus: false,
  billStatus: "",
};

const reducer = (state, action) => {
  switch (action.type) {
    case "changeBillModel":
      return {
        ...state,
        billModelStatus: action.status,
      };
    case "changeBillStatus":
      return {
        ...state,
        billStatus: action.bill,
      };
    default:
  }
};

export default function PoiManageList() {
  const [store, dispatch] = useReducer(reducer, initialState);

  let navigation = useNavigate();
  let location = useLocation();
  const { state } = location;

  const [form] = Form.useForm();
  const [data, setData] = useState({
    billing: { promotion: "", paid: "", paymentChannel: "" },
  });

  /**
   * 设置 优惠金额
   */

  useEffect(() => {
    if (store.billStatus != "") {
      /**
       * 执行支付
       */
      console.log("主订单版本", data.version);
      console.log("支付渠道", store.billStatus);
      console.log("支付金额", data.totalPrice - data.billing.promotion);
      console.log("优惠金额", data.billing.promotion);

      const requstObj = {
        version: data.version,
        promotion: data.billing.promotion,
        paid: data.totalPrice - data.billing.promotion,
        paymentChannel: store.billStatus,
      };
      if (requstObj.promotion === null) {
        requstObj.promotion = 0;
      }
      produce(requstObj);
      navigation("/order/list");
      console.log("执行结账");
    } else {
      console.log("支付不能为空");
    }
  }, [store.billStatus]);

  /**
   * 结账
   */
  function produce(values) {
    axios({
      headers: {
        tenantId: 500,
        userId: 11111,
      },
      method: "post",
      url: `http://localhost:9103/order/catering/${state.id}/bill`,
      data: {
        ...values,
      },
    }).then((data) => {
      setData(data.data);
    });
  }
  /**
   * 根据订单id 查询详细
   * @returns
   */
  useEffect(() => {
    axios({
      headers: {
        tenantId: 500,
        userId: 11111,
      },
      method: "get",
      url: `http://localhost:9103/order/catering/${state.id}`,
    }).then((data) => {
      setData(data.data);
    });
  }, []);

  /**
   * 拼接出餐 请求
   * @returns
   */
  function requstJson() {
    const items = data.items.map((item) => {
      return {
        seqNo: item.seqNo,
        version: item.version,
        quantityOnProduce: item.quantity.latest,
      };
    });
    const obj = {
      version: data.version,
      items: items,
    };

    return obj;
  }

  const onFinish = (values) => {
    produce(requstJson());
  };

  const columns = [
    {
      title: "序号",
      render: (item, re, index) => <div>{index + 1}</div>,
    },
    {
      title: "菜品名",
      dataIndex: ["productSnapshotOnPlace", "name"],
    },
    {
      title: "下单数量",
      dataIndex: ["quantity", "onPlace"],
    },
    {
      title: "结账数量",
      dataIndex: ["quantity", "onProduce"],
    },
    {
      title: "单价",
      dataIndex: ["productSnapshotOnPlace", "unitPrice"],
    },
    {
      title: "计量单位",
      dataIndex: ["productSnapshotOnPlace", "unitOfMeasure"],
    },
    {
      title: "总价",
      dataIndex: this,
      render: (text) =>
        text.productSnapshotOnPlace.unitPrice * text.quantity.onProduce,
    },
  ];

  return (
    <div>
      <Form
        form={form}
        name="advanced_search"
        className="ant-advanced-search-form"
        onFinish={onFinish}
        initialValues={{}}
      >
        <Row gutter={24}>
          {head(state)}
          {/** 菜品信息 */}
          <Col span={24}>
            <Row
              style={{
                background: "rgb(223, 220, 220)",
                marginLeft: 20,
                height: 40,
                paddingTop: 8,
              }}
            >
              <Col span={12}> 菜品信息</Col>
              <Col span={6}> 订单总价:{data.totalPrice}</Col>
              <Col span={2}> 优惠金额:</Col>
              <Col span={4}>
                <Input
                  style={{
                    width: 50,
                    height: 30,
                    borderTopLeftRadius: 5,
                    borderTopRightRadius: 5,
                    borderBottomLeftRadius: 5,
                    borderBottomRightRadius: 5,
                  }}
                  onChange={(e) => {
                    data.billing.promotion = e.target.value;
                  }}
                />
                元{" "}
              </Col>
            </Row>
          </Col>
          <Divider />
        </Row>
        <Row style={{ width: "100%" }}>
          <Col span={24}>
            <Table
              pagination={false}
              dataSource={data.items}
              columns={columns}
              rowKey="id"
            />
          </Col>
        </Row>

        <Row style={{ width: "100%" }}>
          <Col span={24} style={{ textAlign: "right" }}>
            <Button
              onClick={() => {
                dispatch({ type: "changeBillModel", status: true });
              }}
              className="ant-btn-color"
              style={{
                paddingLeft: 50,
                paddingRight: 50,
                background: "rgb(247, 211, 9)",
                width: "100%",
              }}
            >
              结账
            </Button>
          </Col>
        </Row>
      </Form>

      <BillModel
        store={store}
        dispatch={dispatch}
        paid={data.totalPrice - data.billing.promotion}
      />
    </div>
  );
}
